import {
  getGeneratorVoByIdUsingGet, useGeneratorUsingPost,
} from '@/services/backend/generatorController';
import { useModel, useParams } from '@@/exports';
import { PageContainer } from '@ant-design/pro-components';

import { COS_HOST } from '@/constants';
import { DownloadOutlined, EditOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Collapse,
  Form,
  Image,
  Input,
  message,
  Row,
  Space,
  Tag,
  Typography,
} from 'antd';
import { saveAs } from 'file-saver';
import { useEffect, useState } from 'react';
import { Link } from 'umi';

export default () => {
  const { id } = useParams();
  const [loading, setLoading] = useState<boolean>(false);
  const [downloading,setDownloading]  = useState<boolean>(false);
  const [data, setData] = useState<API.GeneratorVO>({});
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const [form] = Form.useForm();
  const models = data?.modelConfig?.models ?? [];

  const loadData = async () => {
    if (!id) {
      return;
    }
    setLoading(true);
    try {
      const res = await getGeneratorVoByIdUsingGet({
        id: id,
      });
      setData(res.data ?? {});
    } catch (e: any) {
      message.error('获取失败:' + e.message);
    }
    setLoading(false);
  };
  useEffect(() => {
    if (!id) {
      return;
    }
    loadData();
  }, [id]);
  const tagListView = (tags: string[] | undefined) => {
    if (!tags) return;
    return (
      <div style={{ marginBottom: 8 }}>
        {tags.map((item, index) => (
          <Tag key={index}>{item}</Tag>
        ))}
      </div>
    );
  };
  const downloadButton = data.distPath && currentUser && (
    <Button
      type={"primary"}
      icon={<DownloadOutlined />}
      disabled={downloading}
      onClick={async () => {
        setDownloading(true);
        const  values=form.getFieldsValue();
        const blob = await useGeneratorUsingPost(
          {
            id,
            dataModel:values
          },
          {
            responseType: 'blob',
          },
        );
        const fullPath = COS_HOST + data.distPath;
        saveAs(blob, fullPath.substring(fullPath.lastIndexOf('/') + 1));
        setDownloading(false)
      }}
    >
      生成代码
    </Button>
  );
  return (
    <PageContainer title={<></>} loading={loading}>
      <Card>
        <Row justify="space-between" gutter={[32, 32]}>
          <Col flex={'auto'}>
            <Space size={'large'} align={'center'}>
              <Typography.Title level={4}>{data.name}</Typography.Title>
              {tagListView(data.tags)}
            </Space>
            <Typography.Paragraph>{data.description}</Typography.Paragraph>
            <div style={{ marginBottom: 24 }}></div>
            <Form form={form}>
              {models?.map((model, index) => {
                if (model?.groupKey) {
                  if (!model.models) {
                    return <></>;
                  }
                  return (
                    <>
                      <Collapse
                        style={{marginBottom:24}}
                        key={index}
                        defaultActiveKey={[index]}
                        items={[
                          {
                            key: index,
                            label: model.groupName + '（分组）',
                            children: model?.models?.map((subModel, index) => {
                              return (
                                <>

                                  <Form.Item key={index}
                                             // @ts-ignore
                                             name={[model.groupKey,subModel.fieldName]}
                                             label={subModel.fieldName}>
                                    <Input placeholder={subModel.description} />
                                  </Form.Item>
                                </>
                              );
                            }),
                          },
                        ]}

                      />
                    </>
                  );
                }
                return (
                  <>
                    <Form.Item key={index} name={model.fieldName} label={model.fieldName}>
                      <Input placeholder={model.description} />
                    </Form.Item>
                  </>
                );
              })}
            </Form>
            <Space size={'middle'}>
              {downloadButton}
              <Link to={`/generator/detail/${id}`}>
                <Button>查看详情</Button>
              </Link>
            </Space>
          </Col>
          <Col flex="320px">
            <Image src={data.picture}></Image>
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
};
